#include "StdAfx.h"
#include "FileThread.h"

const char* FILENAME = "c:\\filewriting.txt";

FileThread::FileThread()
: fp(NULL)
{
  OutputDebugString("FileThread::FileThread()\n");
}

FileThread::~FileThread()
{
  OutputDebugString("FileThread::~FileThread()\n");

  fclose(fp);
  fp = NULL;
}

void FileThread::run()
{
  OutputDebugString("FileThread::run()\n");

  const char* szData = "Data is being written\r\n";
  open();
  while (!isTerminated()) {
    try {
      if (waitForLock()) {
        OutputDebugString("Writes to file...\n");
        int written = 0;
        if (fp) written = fwrite(szData, 1, strlen(szData), fp);
        if (written != strlen(szData)) throw("Data not written properly");
        releaseLock();
      }
      sleep(1000);
    } catch (...) {
      reopen();
    }
  }
}

void test()
{
  OutputDebugString("Find me! Test\n");
}

void FileThread::open() 
{
  OutputDebugString("FileThread::open()\n");

  while (!fp) {
    fp = fopen(FILENAME, "a+b");
    if (!fp )sleep(1000); // To avoid starvation
  }
}

void FileThread::reopen()
{
  if (fp) {
    fclose(fp);
    fp = NULL;
  }
  open();
}